// 导入保存token的工具函数
import { getToken, removeToken, setToken } from '../../utils/auth.js'
// 导入登录接口
import { login } from '../../api/login.js'
import { getInfo, getMoreInfo, logout } from '@/api/user.js'
// 状态
const state = () => {
  return {
    token: getToken(),
    // 用户信息
    userInfo: {}
  }
}
const mutations = {
  setToken(state, newToken) {
    state.token = newToken
  },
  setUserInfo(state, newUserInfo) {
    state.userInfo = newUserInfo
  }
}
const actions = {
  async login(context, data) {
    // 接口调用的login
    const token = await login(data)
    // 存本地
    setToken(token)
    // 存vuex
    context.commit('setToken', token)
  },
  async getUserInfo(context) {
    const res = await getInfo()
    // console.log('res:',res);
    const moreRes = await getMoreInfo({ id: res.userId })
    context.commit('setUserInfo', { ...res, ...moreRes })
  },
  logout(context) {
    removeToken()
    context.commit('setToken', undefined)
    context.commit('setUserInfo', {})
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
